# -*- coding:utf-8 -*-
import bluetooth
import prettytable as pt
BT_PRPOTOCOL = {1:'SDP', 2:'UDP', 3:'RFCOMM', 4:'TCP', 5:'TCS_BIN', 6:'TCS_AT', 8:'OBEX', 9:'IP', 10:'FTP', 12:'HTTP',
                14:'WSP', 15:'BNEP', 16:'UPNP', 17:'HIDP', 18:'HCRP_CTRL', 20:'HCRP_DATA', 22:'HCRP_NOTE', 23:'AVCTP',
                25:'AVDTP', 27:'CMTP', 29:'UDI', 31:'L2CAP'}

def l2capCon(addr, psm):
    sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
    try:
        sock.connect((addr,psm))
        sock.close()
        return 1
    except Exception,e:
        return 0

def bt_device_type(device_type):
    if device_type == 5898764:
        return '安卓手机'
    if device_type == 7078144:
        return 'computer_ubuntu14'
    if device_type == 786700:
        return 'computer_ubuntu16'
    if device_type == 655620:
        return 'computer_windows'
    if device_type == 2360324:
        return 'headset'
    if device_type == 2360328:
        return 'speaker'
    if device_type == 263208:
        return '智能音箱'
    if device_type == 7995916:
        return '苹果手机'
    if device_type == 3670284:
        return 'MAC 笔记本'
    return 'unknown'


# service scan
def bt_device_service(addr):
     if len(addr) == 17:
        services = bluetooth.find_service(address=addr)
        for svc in services:
           #  status = "on"

            print("Service Name: %s" % svc["name"])
            print("    Host:        %s" % svc["host"])
            print("    Description: %s" % svc["description"])
            print("    Provided By: %s" % svc["provider"])
            print("    Protocol:    %s" % svc["protocol"])
            print("    channel/PSM: %s" % svc["port"])
            print("    svc classes: %s " % svc["service-classes"])
            print("    profiles:    %s " % svc["profiles"])
            print("    service id:  %s " % svc["service-id"])
            print("")
            # protocol scan
            pro = []
            for port in range(1, 31):
                if l2capCon(addr, port):
                    pro.append(BT_PRPOTOCOL[port])
            svc['pro'] = pro
            return svc
        '''
        pro = []
        for port in range(1, 31):
            if l2capCon(addr, port):
                pro.append(BT_PRPOTOCOL[port])
        print "the bt device has those protocol:"'''
        # print pro
        #print tb2
     else:
         print "please enter valid MAC"

if __name__ == '__main__':
    # device scan
    while True:
     bt_device_service("48:2C:A0:0F:1F:AD")

